package com.supor.aiot.basket.ui.basket;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.TimeUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.alipay.mobile.common.share.ShareContent;
import com.android.baseconfig.base.BaseActivity;
import com.android.baseconfig.base.BasePresenter;
import com.android.baseconfig.common.utils.ToastUtils;
import com.supor.aiot.basket.R;
import com.supor.aiot.basket.adapter.IngredientDetailAdapter;
import com.supor.aiot.basket.adapter.IngredientDetailBuyedAdapter;
import com.supor.aiot.basket.api.BasketImpl;
import com.supor.aiot.basket.bean.IngredientDetailBean;
import com.supor.aiot.basket.view.BToast;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.helper.ShareHelper;
import com.supor.aiot.common.utils.MarketUtils;

import org.json.JSONException;

import java.util.concurrent.TimeUnit;


public class IngredientListActivity extends BaseActivity implements View.OnClickListener, IngredientDetailAdapter.OnIngredientChangeListener {

    TextView tvShareCancle;
    TextView tvIngredientsList;
    TextView tvListTime;
    TextView tvSelectAll;
    LinearLayout llIngredientMain;
    RecyclerView rvIngredientList;
    LinearLayout llIngredientOther;
    RecyclerView rvIngredientOther;
    LinearLayout llIngredientCommon;
    RecyclerView rvIngredientCommon;
    LinearLayout llIngredientBuyed;
    RecyclerView rvIngredientBuyed;
    LinearLayout llShareFriend;

    private static final String BATCH_NO = "BATCH_NO";
    private static final String BATCH_TIME = "BATCH_TIME";
    private String BatchNo;
    private String BatchTime;
    private String shareUrl;
    private IngredientDetailBean bean;
    private IngredientDetailAdapter ingredientMainAdapter;
    private IngredientDetailAdapter ingredientOtherAdapter;
    private IngredientDetailAdapter ingredientCommonAdapter;
    private IngredientDetailAdapter ingredientBuyedAdapter;
    private boolean ChangeALL = true;

    @Override
    protected int resourceId() {
        return R.layout.activity_shared_list;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        initIngredientView();
        initChacheData();
        initListener();
    }

    private void initChacheData() {
        BatchNo=getIntent().getStringExtra(BATCH_NO);
        BatchTime=getIntent().getStringExtra(BATCH_TIME);
        if (!TextUtils.isEmpty(BatchNo)){
            ingredientDetail(BatchNo);
            getSharedIngredient(BatchNo);
        }else {
            BToast toast = BToast.makeText(IngredientListActivity.this,R.string.check_error);
            toast.show();
        }
        if (!TextUtils.isEmpty(BatchTime))tvListTime.setText(BatchTime);
    }

    private void initListener() {
        tvShareCancle.setOnClickListener(this);
        tvSelectAll.setOnClickListener(this);
        llShareFriend.setOnClickListener(this);
    }

    private void initRecycleView(IngredientDetailBean bean) {
        if (bean!=null&&bean.getIsMainIngredients()!=null&&bean.getIsMainIngredients().size()>0){
            llIngredientMain.setVisibility(View.VISIBLE);
            ingredientMainAdapter =new IngredientDetailAdapter(bean.getIsMainIngredients(),IngredientListActivity.this);
            LinearLayoutManager layoutManager = new LinearLayoutManager(IngredientListActivity.this);
            layoutManager.setOrientation(RecyclerView.VERTICAL);
            rvIngredientList.setAdapter(ingredientMainAdapter);
            rvIngredientList.setLayoutManager(layoutManager);
            ingredientMainAdapter.setListener(this);
        }else {
            llIngredientMain.setVisibility(View.GONE);
        }

        if (bean!=null&&bean.getIsTsIngredients()!=null&&bean.getIsTsIngredients().size()>0){
            llIngredientOther.setVisibility(View.VISIBLE);
            ingredientOtherAdapter =new IngredientDetailAdapter(bean.getIsTsIngredients(),IngredientListActivity.this);
            LinearLayoutManager layoutManager = new LinearLayoutManager(IngredientListActivity.this);
            layoutManager.setOrientation(RecyclerView.VERTICAL);
            rvIngredientOther.setAdapter(ingredientOtherAdapter);
            rvIngredientOther.setLayoutManager(layoutManager);
            ingredientOtherAdapter.setListener(this);
        }else {
            llIngredientOther.setVisibility(View.GONE);
        }

        if (bean!=null&&bean.getIsCgIngredients()!=null&&bean.getIsCgIngredients().size()>0){
            llIngredientCommon.setVisibility(View.VISIBLE);
            ingredientCommonAdapter =new IngredientDetailAdapter(bean.getIsCgIngredients(),IngredientListActivity.this);
            LinearLayoutManager layoutManager = new LinearLayoutManager(IngredientListActivity.this);
            layoutManager.setOrientation(RecyclerView.VERTICAL);
            rvIngredientCommon.setAdapter(ingredientCommonAdapter);
            rvIngredientCommon.setLayoutManager(layoutManager);
            ingredientCommonAdapter.setListener(this);
        }else {
            llIngredientCommon.setVisibility(View.GONE);
        }

        if (bean!=null&&bean.getIsBuyIngredients()!=null&&bean.getIsBuyIngredients().size()>0){
            llIngredientBuyed.setVisibility(View.VISIBLE);
            ingredientBuyedAdapter =new IngredientDetailAdapter(bean.getIsBuyIngredients(),IngredientListActivity.this);
            LinearLayoutManager layoutManager = new LinearLayoutManager(IngredientListActivity.this);
            layoutManager.setOrientation(RecyclerView.VERTICAL);
            rvIngredientBuyed.setAdapter(ingredientBuyedAdapter);
            rvIngredientBuyed.setLayoutManager(layoutManager);
            ingredientBuyedAdapter.setListener(this);
        }else {
            llIngredientBuyed.setVisibility(View.GONE);
        }

        if (bean!=null&&bean.getIsBuyIngredients()!=null&&bean.getIsBuyIngredients().size()>0&&bean.getIsMainIngredients().size()==0&&bean.getIsCgIngredients().size()==0&&bean.getIsTsIngredients().size()==0){
            ChangeALL=false;
            tvSelectAll.setText(getResources().getString(R.string.cancle_list_all));
        }else {
            ChangeALL=true;
            tvSelectAll.setText(getResources().getString(R.string.select_list_all));
        }
    }

    @SuppressLint("AutoDispose")
    private void ingredientDetail(String batchNo){
        BasketImpl.getInstance().getIngredientDetail(batchNo).subscribe(result -> {
            if (result.isSuccess()) {
                bean=result.data;
                initRecycleView(bean);
            } else {
                Log.e(TAG, "recipe error");
            }
        }, throwable -> {
            Log.e(TAG, "recipe查询失败: " + throwable.getMessage());
        });
    }

    @SuppressLint("AutoDispose")
    private void initIngredientState(String batchNo, int state){
        BasketImpl.getInstance().changeIngredientListBuy(batchNo,state).subscribe(result -> {
            if (result.isSuccess()) {
                ingredientDetail(BatchNo);
            } else {
                Log.e(TAG, "recipe error");
            }
        }, throwable -> {
            Log.e(TAG, "recipe查询失败: " + throwable.getMessage());
        });
    }

    @SuppressLint("AutoDispose")
    private void getSharedIngredient(String batchNo){
        BasketImpl.getInstance().getSharedIngredient(batchNo,3).subscribe(result -> {
            if (result.isSuccess()) {
                shareUrl=result.data;
            } else {
                Log.e(TAG, "SharedIngredient error");
            }
        }, throwable -> {
            Log.e(TAG, "SharedIngredient查询失败: " + throwable.getMessage());

        });
    }

    private void changeAllState(boolean state){
        if (state){
            tvSelectAll.setText(getResources().getString(R.string.select_list_all));
        }else {
            tvSelectAll.setText(getResources().getString(R.string.cancle_list_all));
        }
            initIngredientState(BatchNo,state?0:1);
    }

    private void initIngredientView() {
        tvShareCancle = findViewById(R.id.tv_share_cancle);
        tvIngredientsList = findViewById(R.id.tv_ingredients_list);
        tvListTime = findViewById(R.id.tv_list_time);
        tvSelectAll = findViewById(R.id.tv_select_all);
        rvIngredientList = findViewById(R.id.rv_ingredient_list);
        llShareFriend = findViewById(R.id.ll_share_friend);
        llIngredientMain = findViewById(R.id.ll_main_ingredient);
        rvIngredientList = findViewById(R.id.rv_ingredient_list);;
        llIngredientOther = findViewById(R.id.ll_other_ingredient);
        rvIngredientOther = findViewById(R.id.rv_other_ingredient);
        llIngredientCommon = findViewById(R.id.ll_common_ingredient);
        rvIngredientCommon = findViewById(R.id.rv_common_ingredient);
        llIngredientBuyed = findViewById(R.id.ll_buyed_ingredient);
        rvIngredientBuyed = findViewById(R.id.rv_buyed_ingredient);
        if (MarketUtils.getTools().isInstalled(IngredientListActivity.this, Constants.App.WeixinPackage)) {
            llShareFriend.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId()==R.id.tv_share_cancle){
            IngredientListActivity.this.finish();
        }else if (view.getId()==R.id.tv_select_all){
            ChangeALL=!ChangeALL;
            changeAllState(ChangeALL);
        }else if (view.getId()==R.id.ll_share_friend){
            if (!TextUtils.isEmpty(shareUrl)){
                JSONObject jo = new JSONObject();
                jo.put(Constants.Key.param_shareType, 1);
                jo.put(Constants.Key.param_title, getResources().getString(R.string.share_title_basket));
                jo.put(Constants.Key.param_desc, getResources().getString(R.string.share_desc_basket)+"("+BatchTime.split(" ")[0]+")");
                jo.put(Constants.Key.param_type, 3);
                jo.put(Constants.Key.param_tinyAppShare, 0);
                jo.put(Constants.Key.param_path, shareUrl);
                SuporPresenter.getInstance().sendShareMsg(jo);
            }else {
                ToastUtils.getInstance().showCustomToast(R.string.check_error);
            }
        }
    }

    @Override
    public void OnStateChanged() {
        if (!TextUtils.isEmpty(BatchNo)){
            ingredientDetail(BatchNo);
        }
    }
}
